package com.web.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.web.model.BookInfo;
import com.web.model.JsonVO;
import com.web.service.BookService;

@Controller
@RequestMapping("book")
public class BookController {
	
	@Autowired
	private BookService bookService;
	
	@RequestMapping(value="list")
	@ResponseBody
	public List<JsonVO> list(){
		BookInfo bookInfo = new BookInfo();
		bookInfo.setIsBook(1);  
		bookInfo.setStart(0);
		bookInfo.setLimit(9);
		List<BookInfo> books = bookService.findBooks(bookInfo);
		List<JsonVO> jsons = new ArrayList<JsonVO>();
		for (BookInfo book : books) {
			JsonVO jsonVO = new JsonVO();
			jsonVO.setSrc("1.jpg");
			jsonVO.setTitle(book.getBookName());
			jsons.add(jsonVO);
		}
		return jsons;
	}
	
	@RequestMapping(value = "detail/{id}")
	public String detail(Model model,@PathVariable("id")String id){
		BookInfo bookInfo = new BookInfo();
		bookInfo.setBookId(Long.parseLong(id));
		List<BookInfo> books = bookService.findBooks(bookInfo);
		if (books != null && !books.isEmpty()) {
			bookInfo = books.get(0);
			if (StringUtils.isNotBlank(bookInfo.getTagnames())) {
				bookInfo.setTags(bookInfo.getTagnames().split(","));
			}
			model.addAttribute("book", books.get(0));
		}
		return "detail";
	}
	@RequestMapping(value = "list/byTags/{tagsname}", method = {RequestMethod.GET})
    public ModelAndView findBooksByTag(@PathVariable("tagsname")String tagsname) {
		ModelAndView mav = new ModelAndView("index_");
    	BookInfo bookInfo = new BookInfo();
    	bookInfo.setTagnames(tagsname);
		List<BookInfo> books = bookService.findBooks(bookInfo);
		mav.addObject("books", books);
    	return mav;
    }
}
